package com.dongnam.quanly.web.danhmuc.doitac;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.primefaces.context.RequestContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dongnam.quanly.common.controller.DoiTacController;
import com.dongnam.quanly.common.exceptions.DatabaseException;
import com.dongnam.quanly.common.model.DoiTac;
import com.dongnam.quanly.common.model.KhoHang;
import com.dongnam.quanly.common.model.NhomDoiTac;
import com.dongnam.quanly.common.model.PhieuNhapXuat;
import com.dongnam.quanly.common.model.enumtype.GioiTinh;
import com.dongnam.quanly.common.model.enumtype.LoaiDoiTac;
import com.dongnam.quanly.common.model.enumtype.TuCachPhapNhan;
import com.dongnam.quanly.web.UserBean;
import com.dongnam.quanly.web.danhmuc.nhanvien.NhanVienBean;
import com.dongnam.quanly.web.util.CsvUtil;
import com.dongnam.quanly.web.util.DateFormatUtil;
import com.dongnam.quanly.web.util.WebUtil;

@ManagedBean(name = "DoiTacBean")
@SessionScoped
public class DoiTacBean implements Serializable {

	private static final Logger logger = LoggerFactory.getLogger(NhanVienBean.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@ManagedProperty(value = "#{UserBean}")
	private UserBean userBean;

	// for add doitac
	private DoiTac doiTac;
	private boolean isEdit = false;
	// for download file
	private StreamedContent file;

	// for edit phongBan
	private DoiTac selectedDoiTac;

	private List<DoiTac> listDoiTac;
	private DoiTacController doitacController;

	public DoiTacBean() {
		super();
		doiTac = new DoiTac();
		// TODO Auto-generated constructor stub
	}

	public List<DoiTac> getListDoiTac() {
		if (listDoiTac == null)
			listDoiTac = getDoitacController().findAll();

		return listDoiTac;
	}

	public void setListDoiTac(List<DoiTac> listDoiTac) {
		this.listDoiTac = listDoiTac;
	}

	public DoiTacController getDoitacController() {
		if (doitacController == null)
			doitacController = new DoiTacController();
		return doitacController;
	}

	public void setDoitacController(DoiTacController doitacController) {
		this.doitacController = doitacController;
	}

	public UserBean getUserBean() {
		return userBean;
	}

	public void setUserBean(UserBean userBean) {
		this.userBean = userBean;
	}

	public DoiTac getDoitac() {
		return doiTac;
	}

	public void setDoitac(DoiTac doitac) {
		this.doiTac = doitac;
	}

	public DoiTac getSelectedDoiTac() {
		return selectedDoiTac;
	}

	public void setSelectedDoiTac(DoiTac selectedDoiTac) {
		this.selectedDoiTac = selectedDoiTac;
	}

	public boolean isEdit() {
		return isEdit;
	}

	public void setEdit(boolean isEdit) {
		this.isEdit = isEdit;
	}

	public StreamedContent getFile() {
		return file;
	}

	public void setFile(StreamedContent file) {
		this.file = file;
	}

	public void downloadFileCSV() {

		File excelfile = new File("DOI_TAC.xls");
		List<DoiTac> list = getDoitacController().findAll();
		int length = list.size();
		try {
			WritableWorkbook workbook = Workbook.createWorkbook(excelfile);
			WritableSheet sheet = workbook.createSheet("First Sheet", 0);

			// style for title
			WritableFont titlefont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD);
			WritableCellFormat titleformat = new WritableCellFormat(titlefont);
			titleformat.setAlignment(Alignment.LEFT);
			titleformat.setWrap(false);

			// style for content
			WritableFont contentfont = new WritableFont(WritableFont.ARIAL, 13);
			WritableCellFormat contentformat = new WritableCellFormat(contentfont);
			contentformat.setAlignment(Alignment.LEFT);
			contentformat.setWrap(false);

			// thiet lap tieu de
			sheet.setColumnView(0, 30);
			sheet.setColumnView(1, 30);
			sheet.setColumnView(2, 30);
			sheet.setColumnView(3, 30);
			sheet.setColumnView(4, 30);
			sheet.setColumnView(5, 30);
			sheet.setColumnView(6, 30);
			sheet.setColumnView(7, 30);
			sheet.setColumnView(8, 30);
			sheet.setColumnView(9, 30);
			sheet.setColumnView(10, 30);
			sheet.setColumnView(11, 30);
			sheet.setColumnView(12, 30);
			sheet.setColumnView(13, 30);
			sheet.setColumnView(14, 30);
			sheet.setColumnView(15, 30);
			sheet.setColumnView(16, 30);
			sheet.setColumnView(17, 30);
			sheet.setColumnView(18, 30);
			sheet.setColumnView(19, 30);
			sheet.setColumnView(20, 30);
			sheet.setColumnView(21, 30);
			sheet.setColumnView(22, 30);
			sheet.setColumnView(23, 30);
			sheet.setColumnView(24, 30);

			sheet.addCell(new Label(0, 0, "Mã Đối Tác", titleformat));
			sheet.addCell(new Label(1, 0, "Tên Đối Tác", titleformat));
			sheet.addCell(new Label(2, 0, "Mã nhóm đối tác", titleformat));
			sheet.addCell(new Label(3, 0, "Địa chỉ", titleformat));
			sheet.addCell(new Label(4, 0, "Mã số Thuế", titleformat));
			sheet.addCell(new Label(5, 0, "Mã Ngân Sách", titleformat));
			sheet.addCell(new Label(6, 0, "Điện Thoại", titleformat));
			sheet.addCell(new Label(7, 0, "Fax", titleformat));
			sheet.addCell(new Label(8, 0, "Email", titleformat));
			sheet.addCell(new Label(9, 0, "website", titleformat));
			sheet.addCell(new Label(10, 0, "Diễn Giải", titleformat));
			sheet.addCell(new Label(11, 0, "Số Nợ Tối Đa ", titleformat));
			sheet.addCell(new Label(12, 0, "Hạn nợ", titleformat));
			sheet.addCell(new Label(13, 0, "Tư cách pháp nhân", titleformat));
			sheet.addCell(new Label(14, 0, "Loại Đối Tác", titleformat));

			sheet.addCell(new Label(15, 0, "Người liên hệ", titleformat));
			sheet.addCell(new Label(16, 0, "Giới tính", titleformat));
			sheet.addCell(new Label(17, 0, "Chức danh", titleformat));
			sheet.addCell(new Label(18, 0, "Địa chỉ NLH", titleformat));
			sheet.addCell(new Label(19, 0, "Số CMND", titleformat));

			sheet.addCell(new Label(20, 0, "Ngày cấp CMND", titleformat));
			sheet.addCell(new Label(21, 0, "Nơi cấp CMND", titleformat));
			sheet.addCell(new Label(22, 0, "Email_NLH", titleformat));
			sheet.addCell(new Label(23, 0, "Điện thoại nhà", titleformat));
			sheet.addCell(new Label(24, 0, "Điện thoại di động", titleformat));

			for (int i = 0; i < length; i++) {

				sheet.addCell(new Label(0, i + 1, list.get(i).getMaDoiTac(), contentformat));
				sheet.addCell(new Label(1, i + 1, list.get(i).getTenDoiTac(), contentformat));
				sheet.addCell(new Label(2, i + 1, list.get(i).getNhomDoiTac(), contentformat));
				sheet.addCell(new Label(3, i + 1, list.get(i).getDiaChi(), contentformat));
				sheet.addCell(new Label(4, i + 1, list.get(i).getMaSoThue(), contentformat));
				sheet.addCell(new Label(5, i + 1, list.get(i).getMaNganSach(), contentformat));
				sheet.addCell(new Label(6, i + 1, list.get(i).getDienThoai(), contentformat));
				sheet.addCell(new Label(7, i + 1, list.get(i).getFax(), contentformat));
				sheet.addCell(new Label(8, i + 1, list.get(i).getEmail(), contentformat));
				sheet.addCell(new Label(9, i + 1, list.get(i).getWebsite(), contentformat));
				sheet.addCell(new Label(10, i + 1, list.get(i).getDienGiai(), contentformat));
				sheet.addCell(new Label(11, i + 1, String.valueOf(list.get(i).getSoNoToiDa()), contentformat));
				sheet.addCell(new Label(12, i + 1, String.valueOf(list.get(i).getHanNo()), contentformat));
				sheet.addCell(new Label(13, i + 1, list.get(i).getTuCachPhapNhan().name(), contentformat));
				sheet.addCell(new Label(14, i + 1, list.get(i).getLoaiDoiTac().name(), contentformat));
				sheet.addCell(new Label(15, i + 1, list.get(i).getHoTen(), contentformat));
				sheet.addCell(new Label(16, i + 1, list.get(i).getGioiTinh().name(), contentformat));
				sheet.addCell(new Label(17, i + 1, list.get(i).getChucDanh(), contentformat));
				sheet.addCell(new Label(18, i + 1, list.get(i).getDiaChi_NLH(), contentformat));
				sheet.addCell(new Label(19, i + 1, list.get(i).getSoCMND(), contentformat));
				sheet.addCell(new Label(20, i + 1, list.get(i).getNgayCapCMND() != null ? DateFormatUtil.Date2String(
						"dd-MM-yyyy", list.get(i).getNgayCapCMND()) : "", contentformat));
				sheet.addCell(new Label(21, i + 1, list.get(i).getNoiCapCMND(), contentformat));
				sheet.addCell(new Label(22, i + 1, list.get(i).getEmail_NLH(), contentformat));
				sheet.addCell(new Label(23, i + 1, list.get(i).getDienThoaiNha(), contentformat));
				sheet.addCell(new Label(24, i + 1, list.get(i).getDienThoaiDiDong(), contentformat));

			}

			workbook.write();
			workbook.close();

			file = new DefaultStreamedContent(new FileInputStream(excelfile), "application/csv", "DOI_TAC.xls", "UTF-8");

		} catch (IOException | WriteException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	public void handleFileUpload(FileUploadEvent event) {

		logger.debug("process upload file ");
		Workbook w;
		boolean rollback = false;
		List<DoiTac> list = new ArrayList<DoiTac>();
		try {
			w = Workbook.getWorkbook(event.getFile().getInputstream());
			// Get the first sheet
			Sheet sheet = w.getSheet(0);
			// Loop over first 10 column and lines

			for (int row = 1; row < sheet.getRows(); row++) {

				logger.debug("row " + row);
				Cell cell_MaDoiTac = sheet.getCell(0, row);
				Cell cell_TenDoiTac = sheet.getCell(1, row);
				Cell cell_NhomDoiTac = sheet.getCell(2, row);
				Cell cell_DiaChi = sheet.getCell(3, row);
				Cell cell_MaSoThue = sheet.getCell(4, row);
				Cell cell_MaNganSach = sheet.getCell(5, row);
				Cell cell_DienThoai = sheet.getCell(6, row);
				Cell cell_Fax = sheet.getCell(7, row);
				Cell cell_Email = sheet.getCell(8, row);
				Cell cell_Website = sheet.getCell(9, row);
				Cell cell_dienGiai = sheet.getCell(10, row);
				Cell cell_SoNoToiDa = sheet.getCell(11, row);
				Cell cell_HanNo = sheet.getCell(12, row);
				Cell cell_TuCachPhapNhan = sheet.getCell(13, row);
				Cell cell_LoaiDoiTac = sheet.getCell(14, row);
				Cell cell_HoTen = sheet.getCell(15, row);
				Cell cell_GioiTinh = sheet.getCell(16, row);
				Cell cell_ChucDanh = sheet.getCell(17, row);
				Cell cell_DiaChi_NLH = sheet.getCell(18, row);
				Cell cell_SoCMND = sheet.getCell(19, row);
				Cell cell_NgayCapCMND = sheet.getCell(20, row);
				Cell cell_NoiCapCMND = sheet.getCell(21, row);
				Cell cell_Email_NLH = sheet.getCell(22, row);
				Cell cell_DienThoaiNha = sheet.getCell(23, row);
				Cell cell_DienThoaiDiDong = sheet.getCell(24, row);

				DoiTac dt = new DoiTac();
				dt.setMaDoiTac(cell_MaDoiTac.getContents());
				dt.setTenDoiTac(cell_TenDoiTac.getContents());
				dt.setNhomDoiTac(cell_NhomDoiTac.getContents());
				dt.setDiaChi(cell_DiaChi.getContents());
				dt.setMaSoThue(cell_MaSoThue.getContents());
				dt.setMaNganSach(cell_MaNganSach.getContents());
				dt.setDienThoai(cell_DienThoai.getContents());
				dt.setFax(cell_Fax.getContents());
				dt.setEmail(cell_Email.getContents());
				dt.setWebsite(cell_Website.getContents());
				dt.setDienGiai(cell_dienGiai.getContents());
				dt.setSoNoToiDa(Double.parseDouble(cell_SoNoToiDa.getContents()));
				dt.setHanNo(Double.parseDouble(cell_HanNo.getContents()));
				dt.setTuCachPhapNhan(TuCachPhapNhan.valueOf(cell_TuCachPhapNhan.getContents()));
				dt.setLoaiDoiTac(LoaiDoiTac.valueOf(cell_LoaiDoiTac.getContents()));
				dt.setHoTen(cell_HoTen.getContents());
				dt.setGioiTinh(GioiTinh.valueOf(cell_GioiTinh.getContents()));
				dt.setChucDanh(cell_ChucDanh.getContents());
				dt.setDiaChi_NLH(cell_DiaChi_NLH.getContents());
				dt.setSoCMND(cell_SoCMND.getContents());
				dt.setNgayCapCMND(DateFormatUtil.String2Date("dd-MM-yyyy", cell_NgayCapCMND.getContents()));
				dt.setNoiCapCMND(cell_NoiCapCMND.getContents());
				dt.setEmail_NLH(cell_Email_NLH.getContents());
				dt.setDienThoaiNha(cell_DienThoaiNha.getContents());
				dt.setDienThoaiDiDong(cell_DienThoaiDiDong.getContents());
				list.add(dt);
			}
		} catch (BiffException | IOException e) {
			e.printStackTrace();
			rollback = true;
			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

		if (!rollback) {
			getDoitacController().batchSaveOrUpdate(list);
		}

		listDoiTac = getDoitacController().findAll();
	}

	public GioiTinh[] getListGioiTinh() {
		return GioiTinh.values();
	}

	public LoaiDoiTac[] getListLoaiDoiTac() {
		return LoaiDoiTac.values();
	}

	public TuCachPhapNhan[] getListTuCachPhapNhan() {
		return TuCachPhapNhan.values();
	}

	public void notifyAdd() {
		isEdit = false;
		this.doiTac = new DoiTac();
	}

	public void notifyEdit(DoiTac doitac) {
		isEdit = true;
		this.selectedDoiTac = doitac;
		this.doiTac.fillDoiTac(doitac);
	}

	public void save() {
		RequestContext context = RequestContext.getCurrentInstance();
		try {
			if (isEdit) {
				logger.debug("Edit new DoiTac");

				if (this.selectedDoiTac != null) {

					getDoitacController().makeTransient(this.selectedDoiTac);

					this.selectedDoiTac.fillDoiTac(this.doiTac);
					this.selectedDoiTac.setUpdateBy(userBean.getUser().getUserId());
					getDoitacController().makePersistent(this.selectedDoiTac);

					// change state of parent
					context.addCallbackParam("opSuccess", true);
				}

			} else {

				logger.debug("Add new NhanVien :" + this.doiTac.getMaDoiTac());
				DoiTac dt = new DoiTac();
				dt.setCreateBy(userBean.getUser().getUserId());
				dt.setUpdateBy(userBean.getUser().getUserId());

				dt.fillDoiTac(this.doiTac);

				getDoitacController().makePersistent(dt);
				listDoiTac = getDoitacController().findAll();
				context.addCallbackParam("opSuccess", true);

			}
		} catch (DatabaseException e) {
			e.printStackTrace();
			logger.debug("Database error" + e.getMessage());
			context.addCallbackParam("opSuccess", false);

			FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Unsuccessful : Database error : "
					+ e.getMessage(), "");
			FacesContext.getCurrentInstance().addMessage(null, msg);
		}

	}

	public void removeDoiTac() {

		if (this.selectedDoiTac != null) {
			getDoitacController().makeTransient(this.selectedDoiTac);

			listDoiTac = getDoitacController().findAll();
		}

	}

	public void reloadPage() {

		WebUtil.redirect("/pages/danhmuc/doiTac.xhtml");
	}

	public DoiTac getDoiTac() {
		return doiTac;
	}

	public void setDoiTac(DoiTac doiTac) {
		this.doiTac = doiTac;
	}

}
